#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Created: Tue May 18 21:25:14 2010

from sys import argv, exit
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import rpyc
from widgets.login_groupbox import Ui_Login_groupbox

class LCPMainWindow(QMainWindow):
    def __init__(self, parent = None):
        super(LCPMainWindow, self).__init__(parent)

        # setup Main Window.
        self.setObjectName("LCPMainWindow")
#        self.resize(1045, 650)
        self.setFixedSize(1250, 670)

        # set window icon
        windowIcon = QIcon()
        windowIcon.addPixmap(QPixmap("icons/icon.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(windowIcon)

        self.setWindowTitle('Linux Control Panel')

        # Parse the configuration file.
        self.configList = self.getConfig('modulesList.txt')
        self.login_groupbox = Ui_Login_groupbox(self)

        ################################################
#        self.login_groupbox.txt_loginIP.setText('127.0.0.1')
#        self.login_groupbox.txt_loginPassword.setText('rootpassword')
        ################################################

        # Connecting signals with slots.
        self.connect(self.login_groupbox.btn_login, SIGNAL("clicked()"), self.login)
        self.connect(self.login_groupbox.btn_canclLogin, SIGNAL("clicked()"), self.Cancellogin)


    def getConfig(self, configFilePath):
        '''
        return the modules configuration as a list of tuples, as parsed from the configuration file.
        '''

        configFile = open(configFilePath)
        configList = []

        for line in configFile :
            if line.strip().startswith('#') :
                continue

            elif line.strip() == '' :
                continue

            else :
                tempList = line.strip().split('"')
                itemName = tempList[0].strip().split()[0]
                iconPath = tempList[0].strip().split()[1]
                shortName = tempList[1]
                configList.append((itemName, iconPath, shortName))

        return configList


    def setupUI(self, server):
        '''
        Setup the user interface.
        '''

        self.mainGroupBox = QGroupBox()

        self.listWidget = QListWidget(self.mainGroupBox)
#        self.listWidget.setGeometry(QRect(10, 60, 191, 541))
        self.listWidget.setIconSize(QSize(50, 50))
        self.listWidget.setSizePolicy(20, 10)

        self.hlayout = QHBoxLayout(self.mainGroupBox)
        self.hlayout.addWidget(self.listWidget)

        self.setCentralWidget(self.mainGroupBox)

        self.connect(self.listWidget, SIGNAL("itemSelectionChanged()"), self.switchFrame)

        # Add icons to the side list.
        for frame in self.configList :
            icon = QIcon()
            icon.addPixmap(QPixmap(frame[1]))
            item = QListWidgetItem(self.listWidget)
            item.setIcon(icon)

        # Add text to the side list.
        shortNames = [ configLine[-1] for configLine in self.configList ]
        for i in range(len(shortNames)) :
            self.listWidget.item(i).setText(shortNames[i])


        self.login_groupbox.hide()
        self.listWidget.show()

        # Import all frames and create objects of them.
        framesNames = [ configLine[0] for configLine in self.configList ]
        for frame in framesNames :
            exec('from widgets.' + frame + ' import ' + frame)

            exec('self.' + frame + ' = ' + frame + '(server)')
            exec('self.' + frame + '.hide()')
            self.hlayout.addWidget(eval('self.' + frame))
#            exec('self.' + frame + ' = ' + frame + '(server, self)')

        self.allFrames = [ eval('self.' + frameName) for frameName in framesNames ]
#        for frame in self.allFrames :
#            frame.hide()

        self.FrameInformation.show()
        self.listWidget.setCurrentItem(self.listWidget.item(0))


    def login(self):
        '''
        login on the server, with the IP address and the root password specified on the interface.
        '''

        ipAddr = self.login_groupbox.txt_loginIP.text()
        loginPass = self.login_groupbox.txt_loginPassword.text()

        try :
            # Create a connection to the server.
            server = rpyc.connect(ipAddr, port = 4444)

            # Authenticate the root account.
            server.root.authenticate(loginPass)

        except:
            QMessageBox.critical(self, "Authentication Error!", "Wrong IP or password.")
            return False

        self.setupUI(server)

    def Cancellogin(self):
        '''
        Cancel every thing and exit from the application.
        '''
        exit(0)

    def switchFrame(self):
        '''
        Change the displayed frame according to the selected item on the menu.
        '''

        current = self.listWidget.currentRow()

        allFrames = [ eval('self.' + configLine[0]) for configLine in self.configList ]

        for i in range(len(allFrames)) :
            if i == current :
                allFrames[i].show()

            else :
                allFrames[i].hide()



if __name__ == '__main__':
    app = QApplication(argv)
    abstract_window = LCPMainWindow()
    abstract_window.show()
    app.exec_()
